// MBTI 测试相关 API 封装
// 参考 chatService.ts

const API_BASE = import.meta.env._VITE_API_BASE_URL|| 'http://127.0.0.1:8000';

export interface MbtiQuestion {
  id: string;
  text: string;
  options: Record<string, { text: string }>;
}

export interface MbtiProgress {
  progress: number;
  remaining_questions: number;
}

export interface MbtiResult {
  dominant_type: string;
  confidence: string;
  dimension_analysis: Record<string, [number, number]>;
  cognitive_stack: Record<string, string>;
}

export interface MbtiFormAnswer {
  question: string;
  answer: string;
}

export async function initTest(jwt: string): Promise<{ session_id: string }> {
  const res = await fetch(`${API_BASE}/mbti/init`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${jwt}`,
      'Content-Type': 'application/json',
    },
  });
  if (!res.ok) throw new Error(`初始化失败: ${res.status}`);
  return await res.json();
}

export async function getNextQuestion(sessionId: string, jwt: string): Promise<{ question: MbtiQuestion, progress: number, remaining_questions: number }> {
  const res = await fetch(`${API_BASE}/mbti/next-question/${sessionId}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${jwt}`,
    },
  });
  if (!res.ok) throw new Error(`获取问题失败: ${res.status}`);
  return await res.json();
}

export async function submitAnswer(sessionId: string, jwt: string, questionId: string, option: string): Promise<any> {
  const res = await fetch(`${API_BASE}/mbti/submit-answer/${sessionId}`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${jwt}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ question_id: questionId, option }),
  });
  if (!res.ok) throw new Error(`提交答案失败: ${res.status}`);
  return await res.json();
}

export async function getResult(sessionId: string, jwt: string): Promise<MbtiResult> {
  const res = await fetch(`${API_BASE}/mbti/result/${sessionId}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${jwt}`,
    },
  });
  if (!res.ok) throw new Error(`获取结果失败: ${res.status}`);
  return await res.json();
}

export async function submitForm(sessionId: string, jwt: string, answers: MbtiFormAnswer[]): Promise<{ detailed_analysis: string }> {
  const res = await fetch(`${API_BASE}/mbti/submit-form/${sessionId}`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${jwt}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ answers }),
  });
  if (!res.ok) throw new Error(`获取详细分析失败: ${res.status}`);
  return await res.json();
}
